<template>
  <div class="count">
    <el-input
      v-bind="$attrs"
      :value="state.value"
      @change="handleSetCode"
      class="login-input"
      :prefix-icon="ChatRound"
      placeholder="短信验证码"
      clearable
    />
    <el-button
      plain
      class="codeBtn"
      :disabled="!state.canGetCode"
      @click="getSmsCode"
      >{{ state.btnText }}</el-button
    >
  </div>
</template>

<script lang="ts" setup>
import { ChatRound } from "@element-plus/icons-vue";
import { reactive, onBeforeUnmount } from "vue";

interface StateType {
  value: string;
  btnText: string;
  timer: any;
  canGetCode: boolean;
}
const state: StateType = reactive({
  value: "",
  timer: null,
  canGetCode: true,
  btnText: "获取验证码",
});
// 倒计时 => 更改btnText
const IntervalValue = () => {
  let count = 60;
  state.btnText = count + "秒后重新获取";
  state.timer = setInterval(() => {
    if (count > 1) {
      count--;
      state.btnText = count + "秒后重新获取";
    } else {
      state.canGetCode = true;
      state.btnText = "获取验证码";
      clearInterval(state.timer);
    }
  }, 1000);
};

// 获取code
const getSmsCode = (): void => {
  state.canGetCode = false;
  IntervalValue();
};
const handleSetCode = (e) => {
  state.value = e;
};
// 销毁定时器
onBeforeUnmount(() => {
  clearInterval(state.timer);
});
</script>

<style scoped lang="less">
.count {
  width: 100%;
  display: flex;
  .codeBtn {
    height: auto;
    margin-left: 10px;
  }
  .login-input {
    flex: 1;
  }
}
</style>
